package me.helllp.dake.generator.meta.core;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;

import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;

import lombok.Getter;
import lombok.Setter;

/**
 * 对应java中的类型
 * 
 * @author 林晓明
 *
 */
@Getter
@Setter
public class SmartType {
	private String packageName;
	
	private String simpleName;

	/**
	 * 用于构造泛型类型
	 */
	private List<SmartType> types = Collections.emptyList();

	public SmartType() {
		this(Void.class);
	}

	public SmartType(Class c) {
		this(c.getPackage().getName(), c.getSimpleName());
	}

	public SmartType(Class c, List<SmartType> types) {
		this(c.getPackage().getName(), c.getSimpleName(), types);
	}

	public SmartType(String packageName, String simpleName) {
		this(packageName, simpleName, null);
	}

	public SmartType(String packageName, String simpleName, List<SmartType> types) {
		this.packageName = packageName;
		this.simpleName = simpleName;
		this.types = types;
	}

	private List<TypeName> transferTypes() {
		return Optional.ofNullable(types).map(item -> {
			return item.stream().map(SmartType::build).collect(Collectors.toList());
		}).orElse(null);
	}
	
	public ClassName makeClassName() {
		return ClassName.get(packageName, simpleName);
	}

	public String makeFullName() {
		return packageName + "." + simpleName;
	}

	public TypeName build() {
		List<TypeName> typeNames = transferTypes();
		 
		ClassName className = makeClassName();
		
		if (CollectionUtils.isEmpty(typeNames)) {
			return className;
		}
		return ParameterizedTypeName.get(className, typeNames.stream().toArray(TypeName[]::new));
	}
}
